/**
 * 
 */
package com.kelaite.procurement.controller;

import static java.lang.String.format;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.kelaite.procurement.constants.Constants;
import com.kelaite.procurement.constants.UserTypeEnum;
import com.kelaite.procurement.constants.VendorStatusEnum;
import com.kelaite.procurement.dto.UserDTO;
import com.kelaite.procurement.entity.TUser;
import com.kelaite.procurement.entity.TVendor;
import com.kelaite.procurement.entity.TVendorUser;
import com.kelaite.procurement.exception.BusinessException;
import com.kelaite.procurement.restful.BaseController;
import com.kelaite.procurement.service.UserService;
import com.kelaite.procurement.service.VendorService;
import com.kelaite.procurement.service.VendorUserService;
import com.kelaite.procurement.utils.CurrentUserUtils;
import com.kelaite.procurement.utils.EncryptUtils;
import com.kelaite.procurement.utils.ValidationUtil;

/**
 * @author Allen
 *
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

	@Autowired
	private UserService userService;

	@Autowired
	private VendorService vendorService;

	@Autowired
	private VendorUserService vendorUserService;

	/**
	 * B端用户管理
	 * 
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/index", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String userlist(Model model, TUser userObj) throws Exception {

		try {
			String userName = CurrentUserUtils.getInstance().getUser()
					.getUsername();
			List<TUser> uList = userService.getByProperty("username", userName);
			if (uList.isEmpty()) {
				throw new BusinessException(format("user[%s] not exsist. ",
						userName));
			}
			TUser user = uList.get(0);
			if (user.gettCompany() == null) {
				throw new BusinessException(format(
						"user[%s] not associated with a company. ", userName));
			}
			// 此处应该根据 选择的client进行过滤，后期需要修改
			List<TVendor> vendors = this.vendorService.getByProperty(
					"tSupplier", user.gettCompany());
			TVendor vendor = new TVendor();
			if (!vendors.isEmpty()) {
				vendor = vendors.get(0);
			}
			List<TVendorUser> vendorUserList = new ArrayList<TVendorUser>();
			if (user.getIsCompanyAdmin() == 1) {
				// vendor管理员
				vendorUserList = this.vendorUserService
						.getUsersByVendorOfSupplier(vendor);
			} else {
				// vendor的普通用户，只查看到自己的个人信息
				vendorUserList = this.vendorUserService
						.getUserByVendorOfSupplierAndUser(vendor, user);
			}
			model.addAttribute("vendorUserList", vendorUserList);
			model.addAttribute("user", user);
			model.addAttribute("vendor", vendor);
			model.addAttribute("userObj", userObj);
			return "user/user_index";
		} catch (Exception e) {
			logger.error(e.getMessage());
			return "error";
		}
	}

	/**
	 * B端用户管理(删除用户)
	 * 
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/delete", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String deleteuser(Model model, HttpServletRequest request)
			throws Exception {

		try {
			String userName = CurrentUserUtils.getInstance().getUser()
					.getUsername();
			String uid = request.getParameter("uid");
			TUser user = userService.getObject(Long.parseLong(uid));
			if (user == null) {
				throw new BusinessException(format("user[%s] not exsist. ",
						userName));
			}
			List<TVendorUser> vendorUsers = this.vendorUserService
					.getByProperty("tUser", user);
			if (!vendorUsers.isEmpty()) {
				TVendorUser vendorUser = vendorUsers.get(0);
				if (vendorUser.getStatus().equals(
						Constants.VENDOR_USER_STATUS_ACTIVE)) {
					vendorUser.setStatus(Constants.VENDOR_USER_STATUS_INACTIVE);
					user.setIsDelete(Short.parseShort(String
							.valueOf(Constants.USER_STATUS_DELETED)));
				} else if (vendorUser.getStatus().equals(
						Constants.VENDOR_USER_STATUS_INACTIVE)) {
					vendorUser.setStatus(Constants.VENDOR_USER_STATUS_ACTIVE);
					user.setIsDelete(Short.parseShort(String
							.valueOf(Constants.USER_STATUS_NORMAL)));
				}
				this.vendorUserService.save(vendorUser);
				this.userService.save(user);
			} else {
				String message = "此用户没有关联到Client，请联系管理员！";
				model.addAttribute("errorMsg", message);
			}
			return this.userlist(model, new TUser());
		} catch (Exception e) {
			logger.error(e.getMessage());
			return "error";
		}
	}

	/**
	 * B端用户管理(同意)
	 * 
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/agree", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String agreeuser(Model model, HttpServletRequest request)
			throws Exception {

		try {
			String userName = CurrentUserUtils.getInstance().getUser()
					.getUsername();
			String uid = request.getParameter("uid");
			TUser user = userService.getObject(Long.parseLong(uid));
			if (user == null) {
				throw new BusinessException(format("user[%s] not exsist. ",
						userName));
			}
			@SuppressWarnings("unused")
			String message = "";
			List<TVendorUser> vendorUsers = this.vendorUserService
					.getByProperty("tUser", user);
			if (!vendorUsers.isEmpty()) {
				TVendorUser vendorUser = vendorUsers.get(0);
				vendorUser.setStatus(Constants.VENDOR_USER_STATUS_ACTIVE);
				this.vendorUserService.save(vendorUser);
				if (String.valueOf(Constants.USER_MESSAGE_DELETED).equals(
						String.valueOf(user.getIsDelete()))) {
					user.setIsDelete(Short.parseShort(String
							.valueOf(Constants.USER_MESSAGE_UNDELETED)));
					this.userService.save(user);
				}
			} else {
				message = "此用户没有关联到Client，请联系管理员！";
			}
			return this.userlist(model, new TUser());
		} catch (Exception e) {
			logger.error(e.getMessage());
			return "error";
		}
	}

	/**
	 * B端用户管理(添加用户)
	 * 
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/adduser", method = { RequestMethod.GET,
			RequestMethod.POST })
	public String adduser(@Valid @ModelAttribute("userObj") TUser userObj,
			BindingResult result, Model model) throws Exception {

		// 表单验证
		if (result.hasErrors()) {
			List<ObjectError> list = result.getAllErrors();
			for (int i = 0; i < list.size(); i++) {
				logger.debug("----validation error message:----");
				logger.debug(list.get(i));
			}
			model.addAttribute("formErrors", result.getAllErrors());
			return this.userlist(model, userObj);
		}
		UserDTO userDTO = CurrentUserUtils.getInstance().getUser();
		TUser currentUser = this.userService.getObject(userDTO.getId());
		try {
			List<TVendor> vendors = this.vendorService.getByProperty(
					"tSupplier", currentUser.gettCompany());
			// 进来后默认显示第一家具有关联关系的client
			TVendor currentVendor = vendors.get(0);
			// 验证是否是有效供应商
			if (!String.valueOf(VendorStatusEnum.EFFECTIVE_SUPPLIER.getVal())
					.equals(String.valueOf(currentVendor.getStatus()))) {
				result.addError(new ObjectError("NonEffectiveSupplier",
						"您还不是有效的供应商，不能执行此操作，请与管理员联系!"));
				return this.userlist(model, userObj);
			}
			// 验证是否超过最大用户数
			if (currentVendor.getUsersLimitNum() <= this.vendorUserService
					.getByProperty("tVendor", currentVendor).size()) {
				result.addError(new ObjectError("exceedNumberOfUserLimit",
						"超过最大的用户数,请联系系统管理员!"));
				return this.userlist(model, userObj);
			}
			// 验证用户名是否存在
			if (this.userService.getByProperty("username",
					userObj.getUsername().trim()).size() != 0) {
				result.addError(new ObjectError("userExist", "此用户已经存在，请重新输入!"));
				return this.userlist(model, userObj);
			}
			TUser user = new TUser();
			// 验证用户输入的手机号和邮箱地址
			String[] splitString = userObj.getMobilePhone().split(",");
			if (splitString.length != 2) {
				result.addError(new ObjectError("errorInputForMobileAndEmail",
						"请输入手机号和邮箱，并用逗号隔开！"));
				return this.userlist(model, userObj);
			}
			for (int i = 0; i < splitString.length; i++) {
				if (i == 0) {
					user.setMobilePhone(StringUtils.trim(splitString[i]));
					if (!ValidationUtil.isMobileNumber(user.getMobilePhone())) {
						result.addError(new ObjectError("invalidMobile",
								"用户手机号输入格式有误!"));
						return this.userlist(model, userObj);
					}
					user.setWechat(user.getMobilePhone());
				} else {
					user.setEmail(StringUtils.trim(splitString[i]));
					if (!ValidationUtil.isEmailValid(user.getEmail())) {
						result.addError(new ObjectError("invalidEmail",
								"邮箱地址输入格式有误!"));
						return this.userlist(model, userObj);
					}
				}
			}

			user.setUsername(userObj.getUsername().trim());
			user.setPassword(EncryptUtils.encryptSalt(userObj.getPassword()));
			user.setRealName(userObj.getRealName());
			user.setIsDelete(Short.parseShort("0"));
			user.setLanguage("en");
			user.settCompany(currentUser.gettCompany());
			user.setGmtCreateTime(new Date());
			user.setGmtUpdateTime(new Date());
			user.setType(Short.parseShort(String.valueOf(UserTypeEnum.SUPPLIER
					.getVal())));
			user.setUpdatedBy(currentUser.getUsername());
			user.setIsCompanyAdmin(Constants.IS_COMPANY_ADMIN);
			TUser savedUser = this.userService.save(user);

			TVendorUser vendorUser = new TVendorUser();
			vendorUser.settUser(savedUser);
			vendorUser.settVendor(currentVendor);
			vendorUser
					.setBusinessType(Constants.COMPANY_BUSINESS_TYPE_PARTY_SECOND);
			vendorUser.setStatus(Constants.VENDOR_USER_STATUS_ACTIVE);
			this.vendorUserService.save(vendorUser);
			model.addAttribute("fields", result.getAllErrors());
		} catch (Exception e) {
			logger.error(e.getMessage());
			return this.userlist(model, new TUser());
		}
		return this.userlist(model, new TUser());
	}

	@Override
	protected Class<?> getCurrentClass() {

		return UserController.class;
	}
}
